import dayjs from "dayjs";

export const DATE_FORMATTER = "YYYY-MM-DD";
export const TIME_FORMATTER = "HH:mm:ss";
export const DATE_TIME_FORMATTER = `${DATE_FORMATTER} ${TIME_FORMATTER}`;
export const PICKER_OPTIONS = [
  {
    text: "本周",
    value() {
      return DateUtils.getCurrentWeek();
    },
  },
  {
    text: "上一周",
    value() {
      return [
        dayjs().startOf("week").subtract(1, "week").format(DATE_FORMATTER),
        dayjs().startOf("week").subtract(1, "week").endOf("week").format(DATE_FORMATTER),
      ];
    },
  },
  {
    text: "本月",
    value() {
      return [dayjs().startOf("month").format(DATE_FORMATTER), dayjs().endOf("month").format(DATE_FORMATTER)];
    },
  },
  {
    text: "上一月",
    value() {
      return [
        dayjs().startOf("month").subtract(1, "month").format(DATE_FORMATTER),
        dayjs().startOf("month").subtract(1, "month").endOf("month").format(DATE_FORMATTER),
      ];
    },
  },
];

export class DateUtils {
  static getFileTime(file: File, prefix: string, suffix: string, format = "YYYY_MM_DD_HH_mm_ss"): dayjs.Dayjs {
    const fileName = file.name;
    const prefixIndex = fileName.indexOf(prefix);
    const suffixIndex = fileName.indexOf(suffix);
    const time = fileName.slice(prefixIndex + prefix.length, suffixIndex).split("(")[0];
    return dayjs(time, format);
  }

  /**
   * 获取日期区间
   * @param startOffset 起始日期偏移
   * @param endOffset 结束日期偏移
   * @param formatter
   * @returns {(string|string)[]}
   */
  static getRange(startOffset = 0, endOffset = 0, formatter: string = DATE_TIME_FORMATTER): string[] {
    const start = dayjs().startOf("day").subtract(startOffset, "day");
    const end = dayjs().endOf("day").subtract(endOffset, "day");
    return [start.format(formatter), end.format(formatter)];
  }

  static getCurrentWeek(): [string, string] {
    return [dayjs().startOf("week").format(DATE_FORMATTER), dayjs().endOf("week").format(DATE_FORMATTER)];
  }
}

export const totalLeagueOfTimeRange = (start: dayjs.Dayjs, end: dayjs.Dayjs) => {
  let i = 0;
  let offset = start;
  do {
    const weekDay = offset.day();
    //周五2场
    if (weekDay === 5) {
      i += 2;
    }
    //周六一场
    if (weekDay === 6) {
      i += 1;
    }
    offset = offset.add(1, "day");
  } while (offset.isBefore(end) || offset.format(DATE_FORMATTER) === end.format(DATE_FORMATTER));

  return i;
};
